#pragma once
#include<iostream>
#include <pthread.h>

namespace MutexModule
{
    class Mutex
    {
    public:
        Mutex()
        {
            pthread_mutex_init(&_mutex, nullptr);
        }
        void Lock()
        {
            int n = pthread_mutex_lock(&_mutex);
            if (n != 0)
            {
                std::cout << "lock error" << std::endl;
                exit(1);
            }
        }
        void UnLock()
        {
            int n = pthread_mutex_unlock(&_mutex);
            if(n != 0)
            {   
                std::cout<< "unlock error" <<std::endl;
                exit(1);
            }
        }
        //提供一个接口，方便条件变量来用
        pthread_mutex_t *Get()
        {
            return &_mutex;
        }
        ~Mutex() 
        {
            pthread_mutex_destroy(&_mutex);
        }
    
    private:
        pthread_mutex_t _mutex;
    };

    //虽然已经对锁进行了封装，但是还是不够方便，这里直接再封装一层
    class MutexGuard//不用手动的去摧毁锁，自动调用上面的析构函数
    {
    public:
        MutexGuard(Mutex* mutex)
        :_Mutex(mutex)
        {
            _Mutex->Lock();
        }
        ~MutexGuard()
        {
            _Mutex->UnLock();
        }
    private:
        Mutex* _Mutex;
    };

}
